package cn.jisol.ngame.actions.frame;

import cn.jisol.ngame.actions.frame.client.NFrameSyncClient;
import cn.jisol.ngame.ncall.NCallServiceImpl;
import cn.jisol.ngame.rpc.NGameRPCClass;
import cn.jisol.ngame.rpc.NGameRPCMethod;
import cn.jisol.ngame.rpc.NRPCParam;
import cn.jisol.ngame.sync.NFPSInfo;
import cn.jisol.ngame.sync.fps.NSyncFPSMethod;
import cn.jisol.ngame.sync.fps.NSyncFPSMode;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
@NGameRPCClass
public class SNFrameSyncAction extends NCallServiceImpl {
    
    //同步nSyncModes
    public NSyncFPSMode<Object> nSyncFPSMode = null;
    
    //客户端列表
    public Map<String, NFrameSyncClient> clients = null;
    
    /**
     * 启动帧同步
     */
    @NGameRPCMethod
    public void nGameSyncStart(){
        
        if(Objects.nonNull(nSyncFPSMode)) return;
        
        //创建帧同步对象
        nSyncFPSMode = new NSyncFPSMode<>();
        nSyncFPSMode.setIntervalTime(66); //设置同步帧
        //添加同步功能
        addRegister(nSyncFPSMode);
        
        //开启同步
        nSyncFPSMode.start();
        System.out.println("SNFrameSyncAction - nGameSyncStart : 开始同步模式");
        
    }

    /**
     * 关闭帧同步
     */
    @NGameRPCMethod
    public void nGameSyncEnd(){

        if(Objects.isNull(this.nSyncFPSMode)) return;

        this.nSyncFPSMode.end();
        this.nSyncFPSMode = null;

        System.out.println("SNFrameSyncAction - nGameSyncEnd : 关闭同步模式");

    }

    /**
     * 向帧同步添加输入
     * @param inputs 输入
     */
    @NGameRPCMethod
    public void nGameFrameInput(@NRPCParam("inputs") List<Object> inputs){
        if(Objects.isNull(nSyncFPSMode)) return;
        nSyncFPSMode.addFPSInfos(inputs);
    }
    /**
     * 同步模式回调
     */
    @NSyncFPSMethod
    public void nGameSyncCallBack(String uuid, NFPSInfo<Object> nFPSInfo){
        
        if(Objects.isNull(clients)) return;
        
        //向所有客户端 发送帧数据
        clients.values().forEach(client -> {
            client.getCnFrameSyncAction().nGameSyncInputCallBack(nFPSInfo);
        });
        
    }
    
}
